package com.yuqiangz.callable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author 赵雨强
 * @create 2021/7/11 8:58
 * @description runnable 和 callable 用法对比
 */


public class Demo1 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        new Thread(new MyThread1(), "AA").start();
        // 这样是不行的
        // ew Thread(new MyThread2(), "BB").start();

        FutureTask<Integer> futureTask1 = new FutureTask<>(new MyThread2());
        FutureTask<Integer> futureTask2 = new FutureTask<>(() -> {
            System.out.println(Thread.currentThread().getName() + " come in callable");
            Thread.sleep(2000);
            return 1024;
        });



        //创建一个线程
        new Thread(futureTask2,"lucy").start();
        new Thread(futureTask1,"mary").start();

        while(!futureTask2.isDone()) {
            System.out.println("wait.....");
        }
        //调用FutureTask的get方法
        System.out.println(futureTask2.get());
        System.out.println(futureTask1.get());

        System.out.println(Thread.currentThread().getName()+" come over");
    }
}


class MyThread1 implements Runnable{

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        System.out.println("runnable方法的run");
    }
}


class MyThread2 implements Callable<Integer>{

    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    @Override
    public Integer call() throws Exception {
        System.out.println(Thread.currentThread().getName()+ "callable接口");
        return 200;
    }
}
